package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.Setmeal_dishMapper;
import com.sky.mapper.dish_flavorMapper;
import com.sky.result.PageResult;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private dish_flavorMapper dfMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private Setmeal_dishMapper setmeal_dishMapper;
    public List<Dish> getBy_category_id(Integer id){
        return dishMapper.getBycate_id(id);
    }
    public PageResult getBypage(DishPageQueryDTO dto){
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<Dish> page = dishMapper.geyBy_page(dto);
        Long totals = page.getTotal();
        List<Dish> records = page.getResult();
        for(int k = 0;k<records.size();k++){
            String dishcategoryname = categoryMapper.getnamebycategoryid(records.get(k).getCategoryId());
            records.get(k).setCategoryName(dishcategoryname);
        }//设置菜品分类名称
//        int k;
//        for(k=0;k<records.size();k++){
//            Dish dish = records.get(k);
//            String dish_category = categoryMapper.getCategoryName_by_Categoryid(dish.getCategoryId());
//            records.get(k).set
//        }
        return new PageResult(totals,records);
    }
    public void start_or_stop(Integer status,Long id){
        dishMapper.startOrstop(status,id);
    }

    public DishVO getByid(Long id){
        Dish dish = dishMapper.getdish(id);//拿到对应id的菜品
        List<DishFlavor> dishflavors = dfMapper.getflavors(id);//拿到该菜品下的对应口味
        String categoryName = categoryMapper.getCategoryName_by_Categoryid(dish.getCategoryId());//根据菜品中的分类id查分类表拿到菜品分类名
        DishVO result = new DishVO();
        result.setCategoryId(dish.getCategoryId());
        result.setCategoryName(categoryName);
        result.setDescription(dish.getDescription());
        result.setFlavors(dishflavors);
        result.setId(dish.getId());
        result.setImage(dish.getImage());
        result.setName(dish.getName());
        result.setPrice(dish.getPrice());
        result.setStatus(dish.getStatus());
        result.setUpdateTime(dish.getUpdateTime());
        return result;


    }
    @Transactional
    public void add(DishDTO dto){
        List<DishFlavor> dishflavor = new ArrayList<DishFlavor>();
        dishflavor = dto.getFlavors();
        Dish dish = new Dish();
        dish.setCategoryId(dto.getCategoryId());
        dish.setImage(dto.getImage());
        dish.setPrice(dto.getPrice());
        dish.setName(dto.getName());
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        if( dto.getStatus()!=null )dish.setStatus(dto.getStatus());
        if( dto.getDescription()!=null )dish.setDescription(dto.getDescription());
        if( dto.getId()!=null )dish.setId(dto.getId());
        dishMapper.insert(dish);
        if( dto.getId() == null ) {
            int i;
            Long id = dishMapper.getidbyname(dto.getName());
            for(i=0;i<dishflavor.size();i++){
                log.info("菜品的id:{}",id);
                dishflavor.get(i).setDishId(id);
                dfMapper.insert(dishflavor.get(i));
            }
        }//处理若传入的菜品id为空
        else{
            int k ;
            for (k=0;k<dishflavor.size();k++){
                DishFlavor obj = dishflavor.get(k);
                dfMapper.insert(obj);
            }
        }

    }
    @Transactional
    public  void update(DishDTO dto){
        Long id = dto.getId();
        Dish dish = new Dish();
        int k = 0;
        dish.setId(id);
        dish.setStatus(dto.getStatus());
        dish.setImage(dto.getImage());
        dish.setPrice(dto.getPrice());
        dish.setDescription(dto.getDescription());
        dish.setName(dto.getName());
        dish.setCategoryId(dto.getCategoryId());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.update(dish);
        List<Long> list_id = dfMapper.getidBydish_id(id);//返回该菜品对应的多条口味数据的id
        for(;k<dto.getFlavors().size();k++){
            dfMapper.update(dto.getFlavors().get(k),id,list_id.get(k));//通过dish_id和id定位某个菜品的口味，从而实现修改的菜品口味不会被覆盖掉，能一一对应上
        }
    }

    @Transactional
    //删除菜品前，应判断是否为起售状态
    // 还要检查是否关联了套餐，若关联不能删除
    public void delete(String ids) throws DeletionNotAllowedException{
        String [] id = ids.split(",");
        List<Dish> list = dishMapper.getdishesByids(id);
        for(int k = 0;k < list.size();k++){
            Dish dish = list.get(k);
            Integer check_id = setmeal_dishMapper.getnameBydishid(dish.getId());
            if( dish.getStatus() == StatusConstant.ENABLE && check_id == null){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            else if(check_id != null){
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        dishMapper.delete_dishes(id);
    }

    @Transactional
    public List<DishVO> getBycategoryid(Integer categoryid){
        List<Dish> dish_list = dishMapper.getBycate_id(categoryid);//拿到了categoryid的所有菜品
        List<DishVO> VOlist = new ArrayList<>();
        List<DishFlavor> dish_flavors = new ArrayList<>();
        log.info("菜品个数:{}",dish_list.size());
        int k = 0;
        for(;k<dish_list.size();k++){
            dish_flavors = dfMapper.getflavors(dish_list.get(k).getId());//拿到一个菜品的所有口味
            DishVO vo = new DishVO();
            vo.setFlavors(dish_flavors);
            BeanUtils.copyProperties(dish_list.get(k),vo);
            VOlist.add(vo);
            //BeanUtils.copyProperties(vo,VOlist.get(k));//封装到volist
        }
        return VOlist;

    }
}
